package org.chromium.tool.net.retrofit;


import org.chromium.tool.bean.BaseBean;

import io.reactivex.FlowableTransformer;
import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by myh on 2019/12/16.
 */

public class RxUtils {
    /**
     * 统一线程处理
     *
     * @param <T> 指定的泛型类型
     * @return FlowableTransformer
     */
    public static <T> FlowableTransformer<T, T> rxFlSchedulerHelper() {
        return flowable -> flowable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 统一线程处理
     *
     * @param <T> 指定的泛型类型
     * @return ObservableTransformer
     */
    public static <T> ObservableTransformer<T, T> rxSchedulerHelper() {
        return observable -> observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 统一返回结果处理
     *2003支付失败
     * @param <T> 指定的泛型类型
     * @return ObservableTransformer
     */
    public static <T> ObservableTransformer<BaseBean<T>, BaseBean<T>> handleResult() {
        return httpResponseObservable ->
                httpResponseObservable.flatMap((Function<BaseBean<T>, Observable<BaseBean<T>>>) baseResponse -> {
                    if (baseResponse.getNewCode()==200||baseResponse.getNewCode()==2000||baseResponse.getNewCode()==2001
                            ||baseResponse.getNewCode()==2002||baseResponse.getNewCode()==3001||baseResponse.getNewCode()==2003
                           ) {//todo 测试上线记得改过来
                        if (baseResponse.getNewData() == null) {
                            baseResponse.setNewData((T) new Object()); ;
                        }
                        return createData(baseResponse);
                    } else {
                        return Observable.error(new ApiException(baseResponse.getNewCode(),baseResponse.getMsg(),baseResponse.getErrMsg()));
                    }
                });
    }






    /**
     * 得到 Observable
     *
     * @param <T> 指定的泛型类型
     * @return Observable
     */
    private static <T> Observable<BaseBean<T>> createData(final BaseBean<T> t) {

        return Observable.create(emitter -> {
            try {
                emitter.onNext(t);
                emitter.onComplete();
            } catch (Exception e) {
                emitter.onError(e);
            }
        });
    }

    /**
     * 泛型转换工具方法 eg:object ==> map<String, String>
     *
     * @param object Object
     * @param <T>    转换得到的泛型对象
     * @return T
     */
    @SuppressWarnings("unchecked")
    public static <T> T cast(Object object) {
        return (T) object;
    }
}